module Skit
  module Health
    class Middleware
      def initialize(app, url = '/skit_health/check', &check)
        @app, @url, @check = app, url, check
      end

      def call(env)
        run_check?(env) ? run : @app.call(env)
      end

      private

      def run_check?(env)
        env['PATH_INFO'] == @url
      end

      def run
        result = Skit::Health.run_check(@check)

        [ 200,
          { 'Content-Type' => 'text/plain',
            'Content-Length' => result.length.to_s
          },
          [result]
        ]
      end
    end
  end
end
